# $Id: trap.sh.in 815 2008-12-05 22:23:24Z enki $
#
# shell/trap.sh: functions for dealing with shell traps (signal handling)
#
# -------------------------------------------------------------------------
test $lib_shell_trap_sh || {

# directory setup
# -------------------------------------------------------------------------
: ${prefix:="@prefix@"}
: ${exec_prefix:="@prefix@"}
: ${libdir:="${exec_prefix}/lib"}
: ${shlibdir:="${libdir}/sh"}

# load dependencies
# -------------------------------------------------------------------------
. $shlibdir/std/str.sh
. $shlibdir/std/escape.sh

# -------------------------------------------------------------------------
trap_delim=';'
trap_signals=(SIG{HUP,INT,QUIT,ILL,TRAP,ABRT,BUS,FPE,KILL,USR1,SEGV,USR2,\
PIPE,ALRM,TERM,STKFLT,CHLD,CONT,STOP,TSTP,TTIN,TTOU,URG,XCPU,XFSZ,VTALRM,\
PROF,WINCH,IO,PWR,SYS})

# trap_cmds <signal-name>
# -------------------------------------------------------------------------
trap_cmds()
{
  local ts=`trap -p "$1"` IFS=""

  eval "set -- `escape_dquote "$ts"`"

  test "$3" &&
  echo "$3"
}

# trap_isset <signal-name>
# -------------------------------------------------------------------------
trap_isset()
{
  local tn IFS="
"
  for tn in `trap_list`; do
    if [ "${tn#SIG}" = "${1#SIG}" ]; then
      return 0
    fi
  done
  
  return 1
}

# trap_set <commands> <signal-names...>
# -------------------------------------------------------------------------
trap_set()
{
  local cmds=`str_escape "$1"`

  shift

  trap -- "$cmds" "$@"
}

# trap_add <commands> <signal-names...>
# -------------------------------------------------------------------------
trap_add()
{
  local add=`escape_dquote "$1"` cmds sig

  shift

  for sig; do
    cmds=`trap_cmds "$sig"`

    trap "${cmds:+"$cmds"${add:+"$trap_delim"}}$add" "$sig"
  done
}

# trap_unset <signal-names...>
# -------------------------------------------------------------------------
trap_unset()
{
  trap - "$@"
}

# trap_list
#
# List names of all signals trapped.
# -------------------------------------------------------------------------
trap_list()
{
  local t IFS="
"
  for t in \
    $(traps=`trap -p` && echo "$traps" |
    #sed -e "/\\\\'/" |
    sed -e "/'/ {
      :lp
      /'.*'/! {
        N
        b lp
      }
      s/'[^']*'/:/g
    }")
  do
    eval "set -- $t" && echo "$4"
  done
}

# --- eof ---------------------------------------------------------------------
lib_shell_trap_sh=:;}
